﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DAL;
using BLL;

namespace CTRL
{
    public sealed class CtrlBookingItem
    {
        private static volatile CtrlBookingItem instance;
        private static object syncRoot = new Object();

        private IDALBookingItem bookingItemRepository;

        private CtrlBatteryItem ctrlBatteryItem;

        public CtrlBookingItem()
        {
            this.bookingItemRepository = new DALBookingItem(new CarBatteryEntities());

            ctrlBatteryItem = CtrlBatteryItem.Instance;
        }

        public static CtrlBookingItem Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new CtrlBookingItem();
                    }
                }

                return instance;
            }
        }

        public IEnumerable<BookingItem> GetBookingItemsFromBooking(int bookingID)
        {
            return bookingItemRepository.GetBookingItemsFromBooking(bookingID);
        }

        public BookingItem GetBookingItemByID(int bItemID)
        {
            return bookingItemRepository.GetBookingItemByID(bItemID);
        }

        public int AddBookingItem(BatteryItem batteryItem, int bookingID, int stationID)
        {
            bookingItemRepository.AddBookingItem(new BookingItem() { batteryID = batteryItem.batteryID, bookingID = bookingID, stationID = stationID });
            ctrlBatteryItem.UpdateBatteryState(batteryItem, BatteryState.booked);

            return bookingItemRepository.Save();
        }

        public int DeleteBookingItemsFromBooking(int bookingID)
        {
            IEnumerable<BookingItem> listBookingItem = GetBookingItemsFromBooking(bookingID);

            foreach (var item in listBookingItem)
                DeleteBookingItem(item);

            return bookingItemRepository.Save();
        }

        private int DeleteBookingItem(BookingItem item)
        {
            if (item != null)
            {
                bookingItemRepository.DeleteBookingItem(item.bookingItemID);
                ctrlBatteryItem.UpdateBatteryState(item.BatteryItem, BatteryState.available);

                return bookingItemRepository.Save();
            }
            else
                throw new Exception("The BookingItem with the specified ID does not exist");
        }
    }
}